(in-package :gwee)

(defclass switchable-layout (view background-mixin)
  ())

(defgeneric switchable-layout-current-view (view))
(defgeneric (setf switchable-layout-current-view) (to view))

(defmethod switchable-layout-current-view ((view switchable-layout))
  (first (view-subviews view)))

(defmethod (setf switchable-layout-current-view) (to (view switchable-layout))
  "Use hooks to track changes in size of the current subview."
  (when (find to (view-subviews view))
;;     (when (switchable-layout-current-view view)
;;       (remove-hook (resize-hook (switchable-layout-current-view view)) 'switchable-resize-for-current))
    (unless (eq (switchable-layout-current-view view) to)
      (clear-grabs-for (switchable-layout-current-view view)))
    (setf (slot-value view 'subviews) (cons to (delete to (slot-value view 'subviews)))
          (view-needs-update-p view) t)
;;     (add-hook (resize-hook to) 'switchable-resize-for-current)
    ))

(defmethod draw-view ((view switchable-layout))
  (when (switchable-layout-current-view view)
    (draw-view (switchable-layout-current-view view))))

(defmethod key-press-event ((view switchable-layout) key)
  (key-press-event (switchable-layout-current-view view) key))

(defmethod key-release-event ((view switchable-layout) key)
  (key-release-event (switchable-layout-current-view view) key))

(defmethod mouse-press-event ((view switchable-layout) button x y)
  (mouse-press-event (switchable-layout-current-view view) button x y))

(defmethod mouse-release-event ((view switchable-layout) button x y)
  (mouse-release-event (switchable-layout-current-view view) button x y))

(defmethod mouse-motion-event ((view switchable-layout) state x y xrel yrel)
  (mouse-motion-event (switchable-layout-current-view view) state x y xrel yrel))

;; (defun switchable-resize-for-current (switchable dimfn)
;;   "Track the size of the current child."
;;   (funcall `(setf ,dimfn)
;;            (funcall dimfn (switchable-layout-current-view switchable))
;;            switchable))

(defmethod view-visible-subviews ((view switchable-layout))
  (if (view-subviews view)
      (list (car (view-subviews view)))
      (list)))

(defmethod synchronize-width-minimum ((view switchable-layout) (parent view) width height)
  (loop for i in (view-subviews view)
       minimize (synchronize-width i view width height)))

(defmethod synchronize-height-minimum ((view switchable-layout) (parent view) width height)
  (loop for i in (view-subviews view)
       maximize (synchronize-height i view width height)))
